<?php

namespace app\screen\controller\user;

use app\common\controller\Screen;
use app\common\model\work_area\WorkAreaUser;
use app\common\service\haikang\HaikangService;
use thans\jwt\facade\JWTAuth;
use hg\apidoc\annotation as Apidoc;

/**
 * @Apidoc\Title("大屏登录相关")
 */
class Login extends Screen
{
    //中间件不验证的方法
    protected $middleware = [
        'app\\middleware\\Screen' => [
            'except' => ['login']
        ]
    ];

    /**
     * @Apidoc\Title("登录")
     * @Apidoc\Url("/screen/user.Login/login")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("account",type="string",require=true, desc="账号")
     * @Apidoc\Param("password",type="string",require=true, desc="密码")
     * @Apidoc\Returned("data", type="object", desc="对象信息",
     *    @Apidoc\Returned("token", type="string", desc="秘钥"),
     *    @Apidoc\Returned("info", type="object", desc="账号信息--type 1总部 2工区账号 3工点id")
     * )
     */
    public function login()
    {
        try {
            $param = $this->request->param();
            Validate([
                'account|账号' => 'require|length:5,15',
                'password|密码' => 'require|length:5,15',
            ])->check($param);
            $info = new WorkAreaUser();
            $info = $info->where([
                'account' => trim($param['account'])
            ])->field('id,account,type,password,work_area_id,work_area_stand_id,remarks')->find();
            if (empty($info)) throw new \Exception('账号不存在');
            $password = md5(md5($param['password']) . "admin");
            if ($password != $info->password) throw new \Exception('密码错误');
            unset($info->password);
            session('screen', $info);
            $token = JWTAuth::builder([
                'work_area_user' => $info->id,
                'type' => 'screen',
                'user_type' => $info->type
            ]);//参数为用户认证的信息，请自行添加
        } catch (\Exception $e) {
            // 验证失败 输出错误信息
            return $this->ajax(0, $e->getMessage());
        }
        return $this->ajax(1, "登陆成功", [
            'token' => 'bearer ' . $token,
            'info' => $info
        ]);
    }

}